using System;
using System.Collections.Generic;
using System.Text;

namespace Ndo.FenCi
{
    public class FenCiFMM : IFenCiProvider
    {
        private CiTrieNode root = new CiTrieNode('\0');
        public void AddCi(params string[] cis)
        {
            foreach (string ci in cis)
            {
                CiTrieNode node = root;
                foreach (char c in ci)
                {
                    CiTrieNode node2;
                    if(!node.TryGetValue(c, out node2))
                    {
                        node2 = new CiTrieNode(c);
                        node.Add(node2);
                    }
                    node = node2;
                }
                node.IsMatch = true;
            }
        }
        public string[] FenCi(string text)
        {
            List<string> ret = new List<string>();
            int i = 0, i0 = 0;
            while(i<text.Length)
            {
                int i1 = i;
                CiTrieNode node = root;
                for(int j = i; j<text.Length;)
                {
                    CiTrieNode node2;
                    if(!node.TryGetValue(text[j], out node2))
                    {
                        break;
                    }
                    node = node2;
                    j++;
                    if(node.IsMatch)
                    {
                        i1 = j;
                    }
                }
                if(i1!=i)
                {
                    if(i0!=i)
                    {
                        ret.Add(text.Substring(i0, i-i0));
                        i0 = i1;
                    }
                    ret.Add(text.Substring(i,i1-i));
                    i = i1;
                    i0 = i1;
                }
                else
                {
                    i++;
                }
            }
            if(i0!=i)
            {
                ret.Add(text.Substring(i0));
            }
            return ret.ToArray();
        }
    }
}
